package android.homeaccount;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.homeaccount.R;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;

public class Saving extends Activity
{
	Button btDate;
	int mYear;
	int mMonth;
	int mDay;
	
	final int DATE_DIALOG_ID = 0;
	
	final static int RESULT_SS = 40;
	
	EditText etDetail;
    EditText etAmount;
	
	/** Called when the activity is first created. */
    @Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
        setContentView(R.layout.income);
        
        btDate = (Button) findViewById(R.id.btDate);
        etDetail = (EditText) findViewById(R.id.etDetail);
        etAmount = (EditText) findViewById(R.id.etAmount);
        
        Button btSave = (Button) findViewById(R.id.btSave);
        Button btClear = (Button) findViewById(R.id.btClear);
        Button btBack = (Button) findViewById(R.id.btBack);
        
        Intent inboundIntent = getIntent();
        final String login_username = inboundIntent.getExtras().getString("USERNAME");
        
        btDate.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				showDialog(DATE_DIALOG_ID);
			}
        });
        // get the current date
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        // display the current date (this method is below)
        updateDisplay();
        
        btSave.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				String _username = login_username;
				//String _date = etDate.getText().toString();
				String _detail = etDetail.getText().toString();
				String _amount = etAmount.getText().toString();

				// TODO Auto-generated method stub
				if(_detail.equals("") || _amount.equals(""))
				{
					AlertDialog.Builder dialog = new AlertDialog.Builder(v.getContext());
					dialog.setTitle("Error Massage");
					dialog.setMessage("�?ุณยั�?�?รอ�?ราย�?าร�?ม�?�?ร�?");
					dialog.setNeutralButton("Close", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{
							// TODO Auto-generated method stub
						}
					});
					dialog.show();
				}
				else
				{
					HttpClient httpclient = new DefaultHttpClient();
			        HttpPost httppost = new HttpPost("http://10.10.92.44/php/homeaccount_v3/index.php/saving/add_ad_action");
			        //HttpPost httppost = new HttpPost("http://localhost/homeaccount_ci173/index.php/member/mainprofile");
			        //HttpPost httppost = new HttpPost("http://homeaccount.monofocus.in.th/index.php/member/authentication");
					try
					{
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
						
						nameValuePairs.add(new BasicNameValuePair("email", _username));
						//nameValuePairs.add(new BasicNameValuePair("date", _date));
						nameValuePairs.add(new BasicNameValuePair("detail", _detail));
						nameValuePairs.add(new BasicNameValuePair("amount", _amount));
												
						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

						HttpResponse response = httpclient.execute(httppost);
						String responseText = EntityUtils.toString(response.getEntity());

						//Toast.makeText(getBaseContext(), responseText, Toast.LENGTH_LONG).show();
						String success = "Success";
						//String success = "Error!!";

			            if(success.equals(responseText))
			            {
//			            	final String title = getString(R.string.save_title);
//			                final String message = getString(R.string.save_message);
//			                showCloseDialogBox(title, message);
			            	
			            	AlertDialog.Builder dialog = new AlertDialog.Builder(v.getContext());
							dialog.setTitle(R.string.save_title);
							dialog.setMessage(R.string.save_message);
							dialog.setNeutralButton("Close", new DialogInterface.OnClickListener()
							{
								@Override
								public void onClick(DialogInterface arg0, int arg1)
								{
									// TODO Auto-generated method stub
									Intent intent = Saving.this.getIntent();
									setResult(Income1.RESULT_Save, intent);
									finish();
								}
							});
							dialog.show();
			            	
			            	Log.i("Save success", "Save successs");
			            }
			            else
			            {
			            	final String title = getString(R.string.save_failed_title);
			                final String message = getString(R.string.save_failed_message);
			                showCloseDialogBox(title, message);
			                Log.i("Save Failed", "Save Failed");
			            }
					}
					catch(Exception e)
					{
						Log.i("Response", "Can't connect to the server");

						//Toast.makeText(getBaseContext(), "Can't connect to the server", Toast.LENGTH_LONG).show();

						AlertDialog.Builder dialog = new AlertDialog.Builder(v.getContext());
						dialog.setTitle("Connection Error");
						dialog.setMessage("Can't connect to the server");
						dialog.setNeutralButton("Close", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface arg0, int arg1)
							{
								// TODO Auto-generated method stub
							}
						});
						dialog.show();
					}
				}
			}
        });
        
        btClear.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				etDetail.setText("");
				etAmount.setText("");
			}
        	
        });
        
        btBack.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				HttpClient client = new DefaultHttpClient();
				//HttpGet httpGet = new HttpGet();
				
				Intent backIntent = new Intent();
				setResult(Login.RESULT_Back, backIntent);
				finish();
			}
        });
	}
    
    private void updateDisplay()
    {
		// TODO Auto-generated method stub
		btDate.setText(new StringBuilder().append(mYear).append(" : ")
										  .append(mMonth + 1).append(" : ")
										  .append(mDay));
	}
    
    private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener()
    {

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
		{
			// TODO Auto-generated method stub
			mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            updateDisplay();
		}
    };
    
    @Override
	protected Dialog onCreateDialog(int id)
	{
	    switch (id)
	    {
	    case DATE_DIALOG_ID:
	        return new DatePickerDialog(this, mDateSetListener, mYear, mMonth, mDay);
	    }
	    return null;
	}
    
	private void showCloseDialogBox(final String title, final String message)
    {
        Builder setupAlert;
        setupAlert = new AlertDialog.Builder(this).setTitle(title).setMessage(message).setNegativeButton("Close", new DialogInterface.OnClickListener()
        {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// TODO Auto-generated method stub
			}
        });
        setupAlert.show();
    }
	
	protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
		super.onActivityResult(requestCode, resultCode, intent);
		if(resultCode == Saving.RESULT_SS)
		{	
			etDetail.setText("");
			etAmount.setText("");
		}
	}
}